import Vue from 'vue'
import Vuex from 'vuex'
import { fetchLogin } from '@/api'
import { getToken, removeToken, setToken } from '@/utils/ls'

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    token: getToken() || ''
  },
  mutations: {
    setToken (state, newToken) {
      state.token = newToken
      // 存入ls
      setToken(newToken)
    },
    removeToken (state) {
      state.token = ''
      removeToken()
    }
  },
  actions: {
    async asyncLogin ({ commit }, form) {
      // 1. 调用登录接口
      const res = await fetchLogin(form)
      // 2. 提交mutation
      commit('setToken', res.data.token)
    }
  }
})
